<template>
  <div class="login-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>登录</span>
        </div>
      </template>
      <el-form :model="loginForm" :rules="rules" ref="loginFormRef" label-width="80px">
        <el-form-item label="用户名" prop="userName">
          <el-input v-model="loginForm.userName"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="userPwd">
          <el-input type="password" v-model="loginForm.userPwd" show-password></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm('loginFormRef')">登录</el-button>
          <el-button @click="resetForm('loginFormRef')">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import {ref} from 'vue';
import {useRouter} from 'vue-router';
import {ElMessage} from 'element-plus';
import axios from 'axios';

const router = useRouter();

const loginForm = ref({
  userName: '',
  userPwd: '',
});

const rules = ref({
  username: [
    {required: true, message: '请输入用户名', trigger: 'blur'},
  ],
  password: [
    {required: true, message: '请输入密码', trigger: 'blur'},
  ],
});

const submitForm = async (formName) => {
  const params = {
    userName: loginForm.userName,
    userPwd: loginForm.userPwd,
  };
  const result = await axios.get("/api/user/login",{params});
  console.log(result.data);

  if (result.data.code) {
    localStorage.setItem('ID', result.data.data.id);
    localStorage.setItem('token', result.data.data.token);
    ElMessage.success('登录成功');
    router.push('/dashboard/index');
  } else {
    ElMessage.error('登录失败');
    return false;
  }

  // loginFormRef.value.validate((valid) => {
  //   if (valid) {
  //     // 模拟登录成功
  //     ElMessage.success('登录成功');
  //     router.push('/dashboard/index');
  //   } else {
  //     console.log('登录失败');
  //     return false;
  //   }
  // });
};

const resetForm = (formName) => {
  loginFormRef.value.resetFields();
};

const loginFormRef = ref(null);
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background-image: url(../assets/img/loginLogo0.jpg);
  background-size: 100% 100%;
  background-attachment: fixed;
}

.box-card {
  width: 400px;
  opacity: 0.85;
}
</style>
